// pages/weather/weather.js
var util = require('../../utils/util.js');
var apiKeyBaidu = "ElKrMG7r4xq0wfmy0rCvmDOi0I5aKKPy";
Page({
  /**
   * 页面的初始数据
   */
  //weather 初始值用于调试效果，在页面载入时就会自动根据当前的经纬度查询对应城市的天气情况
  data: {
    weather: {
      wendu: 18,
      ganmao: '昼夜温差大，较易发生感冒，适当增减衣服，请注意防护。',
      yesterday: {
        date: '17日 星期四',
        type: '阴',
        fx: '南风',
        fl: '微风级',
        low: '低温8°C',
        high: '高温16°C',
      },
      forecast: [
        {
          date: '18日星期五',
          type: '阴',
          high: '高温16°C',
          low: '低温8°C',
          fengxiang: '南风',
          fengli: '微风级',
        },
        {
          date: '19日星期五',
          type: '阴',
          high: '高温16°C',
          low: '低温8°C',
          fengxiang: '南风',
          fengli: '微风级',
        },
        {
          date: '20日星期五',
          type: '阴',
          high: '高温16°C',
          low: '低温8°C',
          fengxiang: '南风',
          fengli: '微风级',
        },
        {
          date: '21日星期五',
          type: '阴',
          high: '高温16°C',
          low: '低温8°C',
          fengxiang: '南风',
          fengli: '微风级',
        },
        {
          date: '22日星期五',
          type: '阴',
          high: '高温16°C',
          low: '低温8°C',
          fengxiang: '南风',
          fengli: '微风级',
        },
      ]
    },
    today: '2020-11-01',
    city: '北京',
    inputCity: '',
  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    //设置最顶部显示的日期
    this.setData({
      today: util.formatTime(new Date()).split(' ')[0],
    });
    var self = this;
    //通过微信API获取当前经纬度，再通过金纬度获取所在城市
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log('onLoadgetlocation', res);
        //百度获取经纬度所在的城市API: http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding-abroad
        wx.request({
          url: 'http://api.map.baidu.com/reverse_geocoding/v3/',
          //url: 'http://api.map.baidu.com/reverse_geocoding/v3/?location=29.71798%2C106.63043&ak=ElKrMG7r4xq0wfmy0rCvmDOi0I5aKKPy&output=json',
          data: {
            location: res.latitude + ',' + res.longitude,
            ak: apiKeyBaidu,
            output: 'json'
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            console.log('onLoadrequest', res);
            var city = res.data.result.addressComponent.city.replace('市','');
            self.searchWeather(city);
          },
        });
      },
    });
  },

  searchWeather: function (cityName) {
    var self = this;
    //中国天气网API接口 https://blog.csdn.net/x_iya/article/details/52189750
    //中华万年历查询天气API接口（JSON）：
    //http://wthrcdn.etouch.cn/weather_mini?city=北京
    wx.request({
      url: 'http://wthrcdn.etouch.cn/weather_mini',
      data: {
        city: cityName
      },
      header: {
        'Content-Type': 'application/json',
      },
      success: function (res) {
        console.log('searchWeatherrequest', res);
        if (res.data.status == 1002) {
          wx.showModal({
            title: '提示',
            content: '输入的城市名称有误，请重新输入.！',
            showCancel: false,
            success: function (res) {
              self.setData({
                inputCity: '',
              });
            },
          });
        } else {
          var weather = res.data.data;
          var day = '';
          for (var i = 0; i < weather.forecast.length; i++) {
            var d = weather.forecast[i].date;
            //在日期前后增加空格，以形成换行效果
            weather.forecast[i].date = '　' + d.toString().replace('星期', '　星期');
            //fengli字段数据处理
            weather.forecast[i].fengli = weather.forecast[i].fengli.replace(/.*\[(.*)\]\].*/, '$1');
          }
          //昨日风力字段数据处理
          weather.yesterday.fl = weather.yesterday.fl.replace(/.*\[(.*)\]\].*/, '$1');
          self.setData({
            city: cityName,
            weather: weather,
            inputCity: '',
          });
        };
      },
    });
  },
  //获取查询框的输入城市
  inputing: function (e) {
    this.setData({
      inputCity: e.detail.value,
    });
  },
  //点击查询按钮处理函数
  bindSearch: function (e) {
    this.searchWeather(this.data.inputCity);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})